#import "Controller.h"


static void addToolbarItem(NSMutableDictionary *theDict,
							NSString *identifier,
							NSString *label,
							NSString *paletteLabel,
							NSString *toolTip,
							id target,
							SEL settingSelector,
							id itemContent,
							SEL action,
							NSMenu * menu)
{
    NSMenuItem *mItem;
    NSToolbarItem *item = [[[NSToolbarItem alloc] initWithItemIdentifier:identifier] autorelease];
    [item setLabel:label];
    [item setPaletteLabel:paletteLabel];
    [item setToolTip:toolTip];
    [item setTarget:target];
    [item performSelector:settingSelector withObject:itemContent];
    [item setAction:action];
    if (menu!=NULL)
    {
	mItem=[[[NSMenuItem alloc] init] autorelease];
	[mItem setSubmenu: menu];
	[mItem setTitle: [menu title]];
	[item setMenuFormRepresentation:mItem];
    }

    [theDict setObject:item forKey:identifier];
}

@implementation Controller

-(void)awakeFromNib
{
    NSToolbar *toolbar=[[[NSToolbar alloc] initWithIdentifier:@"myToolbar"] autorelease];
    
    toolbarItems=[[NSMutableDictionary dictionary] retain];

    addToolbarItem(toolbarItems,@"Search",@"Search",@"Search",@"Search the server list",self,@selector(setView:),searchView,NULL,NULL);
    addToolbarItem(toolbarItems,@"AddServer",@"Add",@"Add",@"This adds a new server entry",self,@selector(setImage:),[NSImage imageNamed:@"add.tiff"],@selector(addServer:),NULL);
	addToolbarItem(toolbarItems,@"DeleteServer",@"Delete",@"Delete",@"This deletes the selected server entry",self,@selector(setImage:),[NSImage imageNamed:@"delete.tiff"],@selector(deleteServer:),NULL);
    addToolbarItem(toolbarItems,@"ToggleDrawer",@"Drawer",@"Drawer",@"This toggles server details",self,@selector(setImage:),[NSImage imageNamed:@"drawer.tiff"],@selector(toggleDrawer:),NULL);

    addToolbarItem(toolbarItems,@"ConnectSite",@"Site",@"Go to Site",@"Connects to Site URL in external browser",self,@selector(setImage:),[NSImage imageNamed:@"connect_site.tiff"],@selector(goToSiteUrl:),NULL);
    addToolbarItem(toolbarItems,@"ConnectFtp",@"FTP",@"Go to FTP",@"Connects to FTP in external browser",self,@selector(setImage:),[NSImage imageNamed:@"connect_ftp.tiff"],@selector(goToFtpUrl:),NULL);
    addToolbarItem(toolbarItems,@"ConnectDn",@"Domain",@"Connect to Domain",@"Connects to Domain Registrar URL in external browser",self,@selector(setImage:),[NSImage imageNamed:@"connect_domain.tiff"],@selector(goToDnUrl:),NULL);
    addToolbarItem(toolbarItems,@"ConnectHost",@"Host",@"Go to Host",@"Connects to Host URL in external browser",self,@selector(setImage:),[NSImage imageNamed:@"connect_host.tiff"],@selector(goToHostUrl:),NULL);

    addToolbarItem(toolbarItems,@"SendMail",@"Email",@"E-mail Details",@"Creates new e-mail with server details",self,@selector(setImage:),[NSImage imageNamed:@"send_mail.tiff"],@selector(sendMail:),NULL);


    [toolbar setDelegate:self];
    [toolbar setAllowsUserCustomization:YES];
    [toolbar setAutosavesConfiguration: YES]; 
    [toolbar setDisplayMode: NSToolbarDisplayModeIconOnly];
    [theWindow setToolbar:toolbar];
}

// Actions

-(IBAction) addServer:(id)sender
{
	[serverArray add:sender];
}

-(IBAction) deleteServer:(id)sender
{
	[serverArray remove:sender];
}

-(IBAction) toggleDrawer:(id)sender
{
	[drawer toggle:sender];
}

- (IBAction)goToSiteUrl:(id)sender
{
	[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:[siteUrlField stringValue]]];
}

- (IBAction)goToDnUrl:(id)sender
{
	[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:[dnUrlField stringValue]]];
}

- (IBAction)goToFtpUrl:(id)sender
{
/*

tell application "Cyberduck"
	set theServer to "ftp.sentineldesign.net"
	set theUser to "serveradmin@sentineldesign.net"
	set thePassword to "asdfasdf"
	set theProtocol to "ftp"
	set theRemoteFolder to "/domains/sentineldesign.net/html"
	
	set theBrowser to (make new browser)
	with timeout of 300 seconds
		tell (theBrowser)
			set the encoding to "UTF-8"
			set show hidden to false
			connect to theServer with protocol theProtocol as user theUser with password thePassword
			change folder to theRemoteFolder
			disconnect
		end tell
	end timeout
end tell

tell applicaiton "Transmit"
	make new document at before front document
	tell document 1 
		connect to theServer as user theUser with password thePassword with connection type FTP
		set your stuff to theRemoteFolder
	end tell
end tell

*/


	//[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:[ftpUrlField stringValue]]];
	
	NSString *scriptSource = [NSString stringWithFormat:@"tell application \"Finder\" OpenURL \"ftp.sentineldesign.net\"\nbeep 3"];
	
	
	
	/*
	NSString *scriptSource = [NSString stringWithFormat:@"tell application \"Cyberduck\"\nset theBrowser to (make new browser)\nwith timeout of 300 seconds\ntell (theBrowser)\nset the encoding to \"UTF-8\"\nset show hidden to false\nconnect to \"%@\" with protocol \"ftp\" as user \"%@\" with password \"%@\"\nchange folder to \"%@\"\ndisconnect\nend tell\nend timeout\nend tell",
							[ftpUrlField stringValue],
							[ftpUsernameField stringValue],
							[ftpPasswordField stringValue],
							[ftpDirectoryField stringValue]];
	*/
	
	NSAppleScript *playScript;
	playScript = [[NSAppleScript alloc] initWithSource:scriptSource];
	[playScript executeAndReturnError:nil];
	
	
	
}

- (IBAction)goToHostUrl:(id)sender
{
	[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:[hostUrlField stringValue]]];
}

-(IBAction) sendMail:(id)sender
{
	/*
    IBOutlet id siteNameField;
    IBOutlet id siteUrlField;
    IBOutlet id siteNotesField;
	
    IBOutlet id ftpUrlField;
    IBOutlet id ftpDirectoryField;
    IBOutlet id ftpUsernameField;
    IBOutlet id ftpPasswordField;
	
    IBOutlet id dbHostField;
    IBOutlet id dbNameField;
    IBOutlet id dbUsernameField;
    IBOutlet id dbPasswordField;
	
    IBOutlet id hostCompanyField;
    IBOutlet id hostUrlField;
    IBOutlet id hostUsernameField;
    IBOutlet id hostPasswordField;
	
    IBOutlet id dnCompanyField;
    IBOutlet id dnUrlField;
    IBOutlet id dnUsernameField;
    IBOutlet id dnPasswordField;
	*/

	NSString *subject	= [NSString stringWithFormat:@"Server Details for %@", [siteNameField stringValue]];
	NSString *body		= [NSString stringWithFormat:@"%@ Server Info\n(%@)\n%@\n\nFTP Server Info\nURL:\t\t\t%@\nDirectory:\t\t%@\nUsername:\t\t%@\nPassword:\t\t%@\n\nDatabase Info\nHost:\t\t\t%@\nName:\t\t\t%@\nUsername:\t\t%@\nPassword:\t\t%@\n\nHosting Info\nCompany:\t\t%@\nUrl:\t\t\t\t%@\nUsername:\t\t%@\nPassword:\t\t%@\n\nDomain Name Info\nCompany:\t\t%@\nUrl:\t\t\t\t%@\nUsername:\t\t%@\nPassword:\t\t%@\n", 
							[siteNameField stringValue], 
							[siteUrlField stringValue],
							[siteNotesField stringValue],
							
							[ftpUrlField stringValue],
							[ftpDirectoryField stringValue],
							[ftpUsernameField stringValue],
							[ftpPasswordField stringValue],
	
							[dbHostField stringValue],
							[dbNameField stringValue],
							[dbUsernameField stringValue],
							[dbPasswordField stringValue],
	
							[hostCompanyField stringValue],
							[hostUrlField stringValue],
							[hostUsernameField stringValue],
							[hostPasswordField stringValue],
	
							[dnCompanyField stringValue],
							[dnUrlField stringValue],
							[dnUsernameField stringValue],
							[dnPasswordField stringValue]];	
	NSString *urlString = [NSString stringWithFormat:@"mailto:?subject=%@&body=%@", subject, body];
	
	urlString = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)urlString, NULL, NULL, kCFStringEncodingUTF8);
	
	NSURL *url;
	
    // Create the URL.
    url = [NSURL URLWithString:urlString];
	
	// Make string safe.
	//url = (NSURL*) CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, (CFStringRef)url, NULL, kCFStringEncodingUTF8);
	
    assert(url != nil);

    // Open the URL.
    (void) [[NSWorkspace sharedWorkspace] openURL:url];
}

-(BOOL)validateMenuItem:(NSMenuItem *)menuItem
{
    return YES;
}

- (BOOL)validateToolbarItem:(NSToolbarItem *)theItem
{
    return YES;
}

- (void) toolbarWillAddItem: (NSNotification *) notif
{
    NSToolbarItem *addedItem = [[notif userInfo] objectForKey: @"item"];
	
    if ([[addedItem itemIdentifier] isEqual: NSToolbarPrintItemIdentifier])
    {
        [addedItem setToolTip: @"Print your document"];
        [addedItem setTarget: self];
    }
} 

- (NSToolbarItem *)toolbar:(NSToolbar *)toolbar itemForItemIdentifier:(NSString *)itemIdentifier willBeInsertedIntoToolbar:(BOOL)flag
{
    NSToolbarItem *newItem = [[[NSToolbarItem alloc] initWithItemIdentifier:itemIdentifier] autorelease];
    NSToolbarItem *item=[toolbarItems objectForKey:itemIdentifier];
    
    [newItem setLabel:[item label]];
    [newItem setPaletteLabel:[item paletteLabel]];
    if ([item view]!=NULL)
    {
		[newItem setView:[item view]];
    }
    else
    {
		[newItem setImage:[item image]];
    }
    [newItem setToolTip:[item toolTip]];
    [newItem setTarget:[item target]];
    [newItem setAction:[item action]];
    [newItem setMenuFormRepresentation:[item menuFormRepresentation]];

    if ([newItem view]!=NULL)
    {
		[newItem setMinSize:[[item view] bounds].size];
		[newItem setMaxSize:[[item view] bounds].size];
    }

    return newItem;
}

- (NSArray *)toolbarDefaultItemIdentifiers:(NSToolbar*)toolbar
{
    return [NSArray arrayWithObjects:@"AddServer", @"DeleteServer", NSToolbarSeparatorItemIdentifier, @"ToggleDrawer", NSToolbarSeparatorItemIdentifier, @"ConnectSite", @"ConnectHost", @"ConnectFtp", @"ConnectDn", @"SendMail", NSToolbarFlexibleSpaceItemIdentifier,@"Search",nil];
}

- (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar*)toolbar
{
    return [NSArray arrayWithObjects:@"AddServer", @"DeleteServer", @"ToggleDrawer", @"ConnectSite", @"ConnectHost", @"ConnectFtp", @"ConnectDn", @"SendMail", NSToolbarSeparatorItemIdentifier,@"Search", NSToolbarSpaceItemIdentifier,NSToolbarFlexibleSpaceItemIdentifier,nil];
}

- (void) dealloc
{
    [toolbarItems release];
    [super dealloc];
}

@end
